<template>
  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="changeDone(todo.id)" />
      <span v-show="!todo.isEdit">{{ todo.title }}</span>
      <input ref="edit" v-show="todo.isEdit" type="text" :value="todo.title" @blur="editBlur(todo, $event)">
    </label>
    <button class="btn btn-danger" @click="delTodo(todo.id)">删除</button>
    <button v-show="!todo.isEdit" class="btn btn-edit" @click="editTodo(todo)">编辑</button>
  </li>
</template>

<script>
export default {
  name: 'TodoItem',
  props: ['todo'],
  methods: {
    changeDone(id) {
      this.$bus.$emit('changeDone', id)
    },
    delTodo(id) {
      this.$bus.$emit('delTodo', id)
    },
    editTodo(todo) {
      this.$bus.$emit('editTodo', todo)
      this.$nextTick(()=>{
        this.$refs.edit.focus()
      })
    },
    editBlur(todo, e) {
      this.$bus.$emit('editBlur', todo)
      if (!e.target.value.trim()) return alert('输入不能为空')
      this.$bus.$emit('updateTodo', todo.id, e.target.value)
    }
  },
}
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 35px;
  line-height: 35px;
  padding: -1 5px;
  border-bottom: 0px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 5px;
  position: relative;
  top: -2px;
}

li button {
  float: right;
  display: none;
  margin-top: 2px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background-color: #ddd;
}

li:hover button {
  display: block;
}

li input {
  height: 21px;
  font-size: 21px;
}
</style>
